/**
 * 
 */
package fr.gfi.agraf.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.log4j.Logger;

/**
 * Classe gérant les cryptages
 * 
 * @author Fw
 * 
 */
public class CryptageUtils {

	/**
	 * Logger
	 */
	private final static Logger LOGGER = Logger.getLogger(CryptageUtils.class);

	/**
	 * Constructeur
	 */
	private CryptageUtils() {
		// Empty constructeur
	}

	/**
	 * @param chaineACrypter
	 * @return
	 */
	public static String crypterMD5(final String chaineACrypter) {
		if (chaineACrypter != null) {
			final byte[] uniqueKey = chaineACrypter.getBytes();
			byte[] hash = null;

			try {
				// on récupère un objet qui permettra de crypter la chaine
				hash = MessageDigest.getInstance("MD5").digest(uniqueKey);
			} catch (final NoSuchAlgorithmException e) {
				LOGGER.warn("no MD5 support in this VM", e);
			}

			final StringBuilder hashString = new StringBuilder();

			if (hash != null) {
				for (int i = 0; i < hash.length; ++i) {
					final String hex = Integer.toHexString(hash[i]);
					if (hex.length() == 1) {
						hashString.append('0');
						hashString.append(hex.charAt(hex.length() - 1));
					} else {
						hashString.append(hex.substring(hex.length() - 2));
					}
				}
			}

			return hashString.toString();
		}
		return null;
	}

	/**
	 * @param stringToCrypt
	 * @return
	 */
	public static String crypterString(final String stringToCrypt) {
		return crypterMD5(stringToCrypt);
	}

}
